﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text; 
	using UFSoft.UBF.AopFrame;	
	using UFSoft.UBF.Util.Context;
	using ufida.u9.ait.openapi.utils;
    using UFSoft.UBF.Business;
    using UFIDA.U9.CS.Collaboration.Library;
    using UFIDA.U9.Base.Attachment;
    using System.IO;
    using UFIDA.U9.CBO.Pub.Controller;

    /// <summary>
    /// AttachmentImportSV partial 
    /// </summary>	
    public partial class AttachmentImportSV 
	{	
		internal BaseStrategy Select()
		{
			return new AttachmentImportSVImpementStrategy();	
		}		
	}

	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class AttachmentImportSVImpementStrategy : BaseStrategy
	{
		public AttachmentImportSVImpementStrategy() { }

		public override object Do(object obj)
		{
			AttachmentImportSV bpObj = (AttachmentImportSV)obj;

			List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();
			try
			{
				if (bpObj.Data == null || bpObj.Data.Count <= 0)
					throw new Exception("传入参数为空");
				foreach (var dto in bpObj.Data)
				{
                    if (!this.hasAttachment(dto.FileName, dto.EntityFullName, dto.EntityCode))
                    {
                        Attachment att=this.ImportAttachment(dto.FileUrl, dto.FileName, dto.EntityFullName, dto.EntityCode, dto.SaveDir);
                        if(att != null)
                        {
                            CommonArchiveDataDTOData retdto = new CommonArchiveDataDTOData
                            {
                                ID = att.ID,
                                Code = att.FileHandler,
                                Name=att.Title
                            };
                            retlist.Add(retdto);
                        }
                    }
				}
				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch (Exception ex)
			{
				return ResultUtils.error(bpObj, bpObj.Data, ex);
			}
		}

        private bool hasAttachment(string fileName, string entityFullName, string entityCode)
        {
            BusinessEntity entity = EntityUtils.GetBusinessEntity(entityFullName, entityCode);
            if (entity == null)
                throw new Exception($"查找实体失败,EntityFullName:[{entityFullName}],Code:[{entityCode}]");
            Attachment att = Attachment.Finder.Find($"EntityFullName='{entityFullName}' and EntityID={entity.ID} and Title='{fileName}'");
            if (att == null)
                return false;
            else
                return true;
        }

        private Attachment ImportAttachment(string fileUrl, string fileName, string entityFullName, string entityCode, string saveDir)
		{
			//从URL下载文件
			//System.IO.Stream stream = HttpUtils.GetStream(fileUrl);
			string path = U9Utils.GetU9Dir() + $"\\{saveDir}\\{entityFullName}\\{entityCode}\\{fileName}";
			HttpUtils.DownloadFile(fileUrl, path);

            //将文件导入U9
            UFIDA.U9.CS.Common.FileStorage.Storage fileStorage = new UFIDA.U9.CS.Common.FileStorage.Storage();
            FileStream fs = new FileStream(path, FileMode.Open);
            string filehandler = fileStorage.SaveFile(fileName, fs);
            long fileID = 0;
            long entityID = 0;
            BusinessEntity entity = EntityUtils.GetBusinessEntity(entityFullName, entityCode);
            UFIDA.U9.CS.Collaboration.Library.FileInfo fileInfo = null;

            using (ISession session = Session.Open())
            {
                fileInfo = UFIDA.U9.CS.Collaboration.Library.FileInfo.Create();
                fileInfo.CreatedOn = DateTime.Now;
                fileInfo.CreatedBy = PlatformContext.Current.UserID;
                fileInfo.ModifiedBy = PlatformContext.Current.UserID;
                fileInfo.ModifiedOn = DateTime.Now;
                fileInfo.Title = fileName;
                fileInfo.FileName = fileName;
                fileInfo.FileExtension = System.IO.Path.GetExtension(fileName);
                fileInfo.Handler = filehandler;
                fileInfo.FileSize = "0";
                fileInfo.UploadDate = DateTime.Now;
                fileInfo.UploadUser = UFIDA.U9.Base.UserRole.User.Finder.FindByID(long.Parse(PlatformContext.Current.UserID));
                fileInfo.UploadDate = DateTime.Now;
                fileInfo.OwnerEntity_Key = entity.Key;

                //session.InList(fileInfo);
                session.Commit();
            }

            fileID = fileInfo.ID;
            entityID = entity.ID;

            Attachment attachment = null;
            using (ISession session = Session.Open())
            {
                attachment = Attachment.Create();
                attachment.CreatedOn = DateTime.Now;
                attachment.CreatedBy = PlatformContext.Current.UserID;
                attachment.ModifiedBy = PlatformContext.Current.UserID;
                attachment.ModifiedOn = DateTime.Now;
                attachment.Title = fileName;
                attachment.URI = fileName;
                attachment.FileHandler = filehandler;
                attachment.EntityFullName = entityFullName;
                attachment.EntityID = entityID;
                attachment.AttachmentID = fileID;

                //session.InList(attachment);
                session.Commit();
            }

            return attachment;
        }

        #endregion

    }
}